{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "[Learn the Basics](intro.html) ||\n",
        "[Quickstart](quickstart_tutorial.html) ||\n",
        "[Tensors](tensorqs_tutorial.html) ||\n",
        "[Datasets & DataLoaders](data_tutorial.html) ||\n",
        "[Transforms](transforms_tutorial.html) ||\n",
        "[Build Model](buildmodel_tutorial.html) ||\n",
        "[Autograd](autogradqs_tutorial.html) ||\n",
        "**Optimization** ||\n",
        "[Save & Load Model](saveloadrun_tutorial.html)\n",
        "\n",
        "# Optimizing Model Parameters\n",
        "\n",
        "Now that we have a model and data it's time to train, validate and test our model by optimizing its parameters on\n",
        "our data. Training a model is an iterative process; in each iteration (called an *epoch*) the model makes a guess about the output, calculates\n",
        "the error in its guess (*loss*), collects the derivatives of the error with respect to its parameters (as we saw in\n",
        "the [previous section](autograd_tutorial.html)), and **optimizes** these parameters using gradient descent. For a more\n",
        "detailed walkthrough of this process, check out this video on [backpropagation from 3Blue1Brown](https://www.youtube.com/watch?v=tIeHLnjs5U8)_.\n",
        "\n",
        "## Prerequisite Code\n",
        "We load the code from the previous sections on [Datasets & DataLoaders](data_tutorial.html)\n",
        "and [Build Model](buildmodel_tutorial.html).\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from torch import nn\n",
        "from torch.utils.data import DataLoader\n",
        "from torchvision import datasets\n",
        "from torchvision.transforms import ToTensor\n",
        "\n",
        "ROOT = \"E:/sfxData/DeepLearning\"\n",
        "\n",
        "training_data = datasets.FashionMNIST(\n",
        "    root=ROOT,\n",
        "    train=True,\n",
        "    download=True,\n",
        "    transform=ToTensor()\n",
        ")\n",
        "\n",
        "test_data = datasets.FashionMNIST(\n",
        "    root=ROOT,\n",
        "    train=False,\n",
        "    download=True,\n",
        "    transform=ToTensor()\n",
        ")\n",
        "\n",
        "train_dataloader = DataLoader(training_data, batch_size=64)\n",
        "test_dataloader = DataLoader(test_data, batch_size=64)\n",
        "\n",
        "class NeuralNetwork(nn.Module):\n",
        "    def __init__(self):\n",
        "        super(NeuralNetwork, self).__init__()\n",
        "        self.flatten = nn.Flatten()\n",
        "        self.linear_relu_stack = nn.Sequential(\n",
        "            nn.Linear(28*28, 512),\n",
        "            nn.ReLU(),\n",
        "            nn.Linear(512, 512),\n",
        "            nn.ReLU(),\n",
        "            nn.Linear(512, 10),\n",
        "        )\n",
        "\n",
        "    def forward(self, x):\n",
        "        x = self.flatten(x)\n",
        "        logits = self.linear_relu_stack(x)\n",
        "        return logits\n",
        "\n",
        "model = NeuralNetwork()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Hyperparameters\n",
        "\n",
        "Hyperparameters are adjustable parameters that let you control the model optimization process.\n",
        "Different hyperparameter values can impact model training and convergence rates\n",
        "([read more](https://pytorch.org/tutorials/beginner/hyperparameter_tuning_tutorial.html)\\_ about hyperparameter tuning)\n",
        "\n",
        "We define the following hyperparameters for training:\n",
        "\n",
        "- **Number of Epochs** - the number times to iterate over the dataset(迭代数据集的次数)\n",
        "- **Batch Size** - the number of data samples propagated through the network before the parameters are updated(在更新参数之前通过网络传播的数据样本数)\n",
        "- **Learning Rate** - how much to update models parameters at each batch/epoch. Smaller values yield slow learning speed, while large values may result in unpredictable behavior during training. (在每个批次/纪元更新模型参数的数量。较小的值会导致学习速度变慢，而较大的值可能会导致训练期间不可预测的行为。\n",
        "  )\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "epochs = 5\n",
        "batch_size = 64\n",
        "learning_rate = 1e-3  # 0.001\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Optimization Loop\n",
        "\n",
        "Once we set our hyperparameters, we can then train and optimize our model with an optimization loop. Each\n",
        "iteration of the optimization loop is called an **epoch**.\n",
        "\n",
        "Each epoch consists of two main parts:\n",
        " - **The Train Loop** - iterate over the training dataset and try to converge to optimal parameters.\n",
        " - **The Validation/Test Loop** - iterate over the test dataset to check if model performance is improving.\n",
        "\n",
        "Let's briefly familiarize ourselves with some of the concepts used in the training loop. Jump ahead to\n",
        "see the `full-impl-label` of the optimization loop.\n",
        "\n",
        "### Loss Function\n",
        "\n",
        "When presented with some training data, our untrained network is likely not to give the correct\n",
        "answer. **Loss function** measures the degree of dissimilarity of obtained result to the target value,\n",
        "and it is the loss function that we want to minimize during training. To calculate the loss we make a\n",
        "prediction using the inputs of our given data sample and compare it against the true data label value.\n",
        "\n",
        "Common loss functions include [nn.MSELoss](https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html#torch.nn.MSELoss) (Mean Square Error, 均方误差) for regression tasks, and\n",
        "[nn.NLLLoss](https://pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html#torch.nn.NLLLoss) (Negative Log Likelihood, 负对数似然) for classification.\n",
        "[nn.CrossEntropyLoss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html#torch.nn.CrossEntropyLoss) combines ``nn.LogSoftmax`` and ``nn.NLLLoss``.\n",
        "\n",
        "We pass our model's output logits to ``nn.CrossEntropyLoss``, which will normalize the logits and compute the prediction error.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Initialize the loss function\n",
        "loss_fn = nn.CrossEntropyLoss()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Optimizer\n",
        "\n",
        "Optimization is the process of adjusting model parameters to reduce model error in each training step. **Optimization algorithms** define how this process is performed (in this example we use Stochastic Gradient Descent).\n",
        "All optimization logic is encapsulated in  the ``optimizer`` object. Here, we use the SGD optimizer; additionally, there are many [different optimizers](https://pytorch.org/docs/stable/optim.html)\n",
        "available in PyTorch such as ADAM and RMSProp, that work better for different kinds of models and data.\n",
        "\n",
        "We initialize the optimizer by registering the model's parameters that need to be trained, and passing in the learning rate hyperparameter.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Inside the training loop, **optimization happens in three steps**:\n",
        " * Call ``optimizer.zero_grad()`` to reset the gradients of model parameters. Gradients by default add up; to prevent double-counting, we explicitly zero them at each iteration.\n",
        " * Backpropagate the prediction loss with a call to ``loss.backward()``. PyTorch deposits the gradients of the loss w.r.t. each parameter.\n",
        " * Once we have our gradients, we call ``optimizer.step()`` to adjust the parameters by the gradients collected in the backward pass.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "## Full Implementation\n",
        "We define ``train_loop`` that loops over our optimization code, and ``test_loop`` that\n",
        "evaluates the model's performance against our test data.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def train_loop(dataloader, model, loss_fn, optimizer):\n",
        "    size = len(dataloader.dataset)\n",
        "    for batch, (X, y) in enumerate(dataloader):\n",
        "        # Compute prediction and loss\n",
        "        pred = model(X)\n",
        "        loss = loss_fn(pred, y)\n",
        "\n",
        "        # Backpropagation\n",
        "        optimizer.zero_grad()\n",
        "        loss.backward()\n",
        "        optimizer.step()\n",
        "\n",
        "        if batch % 100 == 0:\n",
        "            loss, current = loss.item(), batch * len(X)\n",
        "            print(f\"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]\")\n",
        "\n",
        "\n",
        "def test_loop(dataloader, model, loss_fn):\n",
        "    size = len(dataloader.dataset)\n",
        "    num_batches = len(dataloader)\n",
        "    test_loss, correct = 0, 0\n",
        "\n",
        "    with torch.no_grad():\n",
        "        for X, y in dataloader:\n",
        "            pred = model(X)\n",
        "            test_loss += loss_fn(pred, y).item()\n",
        "            correct += (pred.argmax(1) == y).type(torch.float).sum().item()\n",
        "\n",
        "    test_loss /= num_batches\n",
        "    correct /= size\n",
        "    print(f\"Test Error: \\n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \\n\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We initialize the loss function and optimizer, and pass it to ``train_loop`` and ``test_loop``.\n",
        "Feel free to increase the number of epochs to track the model's improving performance.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "loss_fn = nn.CrossEntropyLoss()\n",
        "optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n",
        "\n",
        "epochs = 10\n",
        "for t in range(epochs):\n",
        "    print(f\"Epoch {t+1}\\n-------------------------------\")\n",
        "    train_loop(train_dataloader, model, loss_fn, optimizer)\n",
        "    test_loop(test_dataloader, model, loss_fn)\n",
        "print(\"Done!\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Further Reading\n",
        "- [Loss Functions](https://pytorch.org/docs/stable/nn.html#loss-functions)\n",
        "- [torch.optim](https://pytorch.org/docs/stable/optim.html)\n",
        "- [Warmstart Training a Model](https://pytorch.org/tutorials/recipes/recipes/warmstarting_model_using_parameters_from_a_different_model.html)\n",
        "\n",
        "\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.9"
    },
    "vscode": {
      "interpreter": {
        "hash": "cf18841ace8313d0bc088ca146c17a6c0040e82121d5cb75c0ea07172309253d"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
